package com.dm.cosdemo;

import android.app.Activity;
import android.os.Environment;

import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;

import java.io.File;

import io.flutter.Log;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;

public class CosUploadPlugin implements MethodChannel.MethodCallHandler {

    public static String CHANNEL = "cos_upload";

    static MethodChannel channel;

    private Activity activity;

    private CosUploadPlugin(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(PluginRegistry.Registrar registrar) {
        channel = new MethodChannel(registrar.messenger(), CHANNEL);
        CosUploadPlugin instance = new CosUploadPlugin(registrar.activity());
        channel.setMethodCallHandler(instance);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        Log.i("==>Java Upload File Called", methodCall.method);
        Object resultObj = null;
        switch (methodCall.method) {
            case "isChinese":
                resultObj = "success";
                result.success(resultObj);
                break;
            case "initCos":
                CosXmlService cosXmlService = CosSessionCredentialProvider(methodCall.argument("tmpSecretId"), methodCall.argument("tmpSecretKey"),
                        methodCall.argument("sessionToken"), methodCall.argument("startTime"), methodCall.argument("expiredTime"),
                        methodCall.argument("region"));
                Log.i("=>Init", cosXmlService.toString());
                uploadFile(cosXmlService, "/sdcard/1111111111.png", "circuit-1300618745",
                        "/fluter.png", result);
                break;
        }
    }


    /**
     * 获取临时秘钥凭证
     *
     * @param tmpSecretId  临时Id
     * @param tmpSecretKey 临时key
     * @param sessionToken 临时Token
     * @param expiredTime  过期时间
     * @param startTime    开始时间
     * @return
     */
    public CosXmlService CosSessionCredentialProvider(String tmpSecretId, String tmpSecretKey,
                                                      String sessionToken, String startTime, String expiredTime, String region) {
        Log.i("CosSessionCredentialProvider Init", String.format("tmpSecretId:%s tmpSecretKey:%s sessionToken:%s expiredTime:%s expiredTime:%s region:%s",
                tmpSecretId, tmpSecretKey, sessionToken, expiredTime, startTime, region));

        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder().setRegion(region).isHttps(false)
                .builder();
        CosSessionCredentialProvider sessionCredentialProvider = new CosSessionCredentialProvider(tmpSecretId,
                tmpSecretKey, sessionToken, Long.valueOf(startTime), Long.valueOf(expiredTime));
        CosXmlService cosXmlService = new CosXmlService(activity, serviceConfig, sessionCredentialProvider);
        return cosXmlService;
    }


    public void uploadFile(CosXmlService cosXmlService, String filePath, String bucket, String cosPath, MethodChannel.Result jniResult) {
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        TransferManager transferManager = new TransferManager(cosXmlService, transferConfig);


        File file1 = new File(Environment.getExternalStorageDirectory(), "/DCIM/Camera/1111111111.png");
        String srcPath = file1.toString();
        Log.i("====>", srcPath);
        Log.i("====>exists", file1.exists() + "");
        Log.i("====>isDirectory", file1.isDirectory() + "");
        Log.i("====>canRead", file1.canRead() + "");


        String uploadId = null;
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath, srcPath, uploadId);
        Log.i("====>canRead", "============wwwwwwwww=========");


        //设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult =
                        (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                Log.i("Upload Success", result.httpMessage);
                Log.i("Upload Success", result.httpCode + "");
                Log.i("Upload Success", result.printResult());
                jniResult.success(result.httpCode);
            }

            @Override
            public void onFail(CosXmlRequest request,
                               CosXmlClientException clientException,
                               CosXmlServiceException serviceException) {
                Log.i("=====>", "上传文件失败了");
                clientException.printStackTrace();
                Log.i("===>", "失败");
                serviceException.printStackTrace();
            }
        });

    }


}